﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using System.Windows.Browser;
using System.Collections.Generic;

namespace Microsoft.ProductivityHub.SilverlightBookshelf
{
	public partial class TopRatedControl : UserControl
	{
        SharePointData sd = null;
        public event Bookshelf.FavoritesUpdated OnFavoritesUpdated;


        public TopRatedControl()
		{
			// Required to initialize variables
			InitializeComponent();
            sd = new SharePointData();
            sd.DataLoadedEvent += new SharePointData.DataLoaded(sd_DataLoadedEvent);
            sd.QueryTopRatedItems();

		}

        void sd_DataLoadedEvent(List<ContentItem> contentItems)
        {
            sd.DataLoadedEvent -= new SharePointData.DataLoaded(sd_DataLoadedEvent);
            topRatedContentControl.ItemsSource = contentItems;

        }

        private void ScrollViewer_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            double offset = scrollView.VerticalOffset - (e.Delta / 3);
            if (offset < 0)
            {
                scrollView.ScrollToVerticalOffset(0);
            }
            else if (offset > scrollView.ExtentHeight)
            {
                scrollView.ScrollToVerticalOffset(scrollView.ExtentHeight);
            }
            else
            {
                scrollView.ScrollToVerticalOffset(offset);
            }
            e.Handled = true;

        }


        private void Title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string docUrl = ((TextBlock)sender).Tag as string;
            if (!String.IsNullOrEmpty(docUrl))
            {
                string currentSiteUrl = ApplicationContext.Current.Url;
                if (!String.IsNullOrEmpty(currentSiteUrl))
                {
                    HtmlPage.Window.Navigate(new Uri(docUrl));
                }
            }

        }

        private void TagFavorite_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string docId = ((TextBlock)sender).Tag as string;
            string currentSiteUrl = ApplicationContext.Current.Url;
            if (!String.IsNullOrEmpty(currentSiteUrl))
            {
                // we have sharepoint context, attempt the script call
                // javascript code to call: javascript:hub10_AddFavorite(@ID) 
                string scriptCall = String.Format("hub10_AddFavorite({0});", docId);
                HtmlPage.Window.Eval(scriptCall);

                this.Dispatcher.BeginInvoke(OnFavoritesUpdated, this);
            }

        }
	}
}